package com.jinxin.platform.cdfaceacs.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdfaceacs.bean.CdfaceacsDevice;
import com.jinxin.platform.cdfaceacs.bean.CdfaceacsOpenRecord;
import com.jinxin.platform.cdfaceacs.bean.CdfaceacsWorker;
import com.jinxin.platform.cdfaceacs.bean.OpenRecord;
import com.jinxin.platform.cdfaceacs.mapper.CdfaceacsDeviceMapper;
import com.jinxin.platform.cdfaceacs.mapper.CdfaceacsOpenRecordMapper;
import com.jinxin.platform.cdfaceacs.mapper.CdfaceacsWorkerMapper;
import com.jinxin.platform.cdfaceacs.redis.RedisUtil;
import com.jinxin.platform.cdfaceacs.rpc.SysUserRpc;
import com.jinxin.platform.cdfaceacs.service.IFaceAcsRecordService;
import com.jinxin.platform.cdfaceacs.utils.DateUtil;
import com.jinxin.platform.cdfaceacs.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-05-20
 * @Author: Lingnan
 **/
@Service
public class FaceAcsRecordServiceImpl implements IFaceAcsRecordService {
    @Autowired
    private CdfaceacsOpenRecordMapper openRecordMapper;
    @Resource
    private IdWorker idWorker;
    @Autowired
    private SysUserRpc sysUserRpc;
    @Autowired
    private CdfaceacsWorkerMapper workerMapper;
    @Autowired
    private CdfaceacsDeviceMapper deviceMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public List<CdfaceacsOpenRecord> list(HashMap param) {
        return openRecordMapper.list(param);
    }

    @Override
    public List<CdfaceacsOpenRecord> listPage(HashMap param) {
        return openRecordMapper.listPage(param);
    }

    @Override
    public List<OpenRecord> listOpenRecord(HashMap param) {
        return openRecordMapper.listOpenRecord(param);
    }

    @Override
    public int listPageCount(HashMap param) {
        return openRecordMapper.listPageCount(param);
    }

    @Override
    public int listOpenRecordCount(HashMap param) {
        return openRecordMapper.listOpenRecordCount(param);
    }

    @Override
    public int countAttendance() {
        return openRecordMapper.countAttendance();
    }

    @Override
    public JsonResult delete(String id) {
        if(StringUtils.isEmpty(id)){
            return JsonResult.error("记录Id不存在");
        }
        int result = openRecordMapper.deleteByKey(id);
        if(result > 0){
            return JsonResult.ok("删除成功","");
        }
        return JsonResult.error("删除失败");
    }

    @Override
    public JsonResult saveOrUpdate(CdfaceacsOpenRecord record) {
        if (record == null){
            return JsonResult.error("参数错误，操作失败");
        }
        String id = record.getId();
        int count;
        String msg = "";
        if(StringUtils.isEmpty(id)){
            record.setId(String.valueOf(idWorker.nextId()));
            //record.setOpenTime(LocalDateTime.now());
            count = openRecordMapper.insert(record);
            msg = "新增成功";
        }else {
            count = openRecordMapper.updateByKey(record);
            msg = "更新成功";
        }
        if(count > 0){
            return JsonResult.ok(msg,"");
        }else {
            return JsonResult.error("操作失败，请重试");
        }
    }

    @Override
    public void updateData(String password, String serialNum, String startTime, String endTime) {
        int maxLength = 1000;
        JsonResult jsonResult = sysUserRpc.faceBrushingRecord(password, "-1", maxLength, 0, startTime, endTime, serialNum);
        if(jsonResult.getSuccess()){
            String dataJsonStr = (String) jsonResult.getData();
            JSONObject dataJson = JSONObject.parseObject(dataJsonStr);
            if(dataJson != null){
                HashMap param =new HashMap();
                param.put("serialNum",serialNum);
                CdfaceacsDevice device = deviceMapper.selectOne(new HashMap());
                Map<String,CdfaceacsWorker> workerMap = new HashMap<>();
                List<CdfaceacsWorker> workerList = workerMapper.list(new HashMap());
                workerList.forEach(worker->{
                    String personId = worker.getPersonId();
                    if(!StringUtils.isEmpty(personId)){
                        workerMap.put(personId,worker);
                    }
                });
                insertData(serialNum, dataJson, device, workerMap);
                JSONObject pageInfoJson = dataJson.getJSONObject("pageInfo");
                int size = pageInfoJson.getInteger("size");
                if(size > 1){ // 页码总数 如果是大于1 说明记录总数大于1000 还要继续查询
                    for (int i = 1; i < size; i++) {
                        JsonResult jsonResult2 = sysUserRpc.faceBrushingRecord(password, "-1", maxLength, i, startTime, endTime, serialNum);
                        if(jsonResult2.getSuccess()){
                            String dataJsonStr2 = (String) jsonResult2.getData();
                            JSONObject dataJson2 = JSONObject.parseObject(dataJsonStr2);
                            insertData(serialNum, dataJson2, device, workerMap);
                        }
                    }
                }
            }
        }
    }

    private void insertData(String serialNum, JSONObject dataJson, CdfaceacsDevice device, Map<String, CdfaceacsWorker> workerMap) {
//        String key = Constant.MODULE_PREX + "latest_faceacs_record_time";
//        String startTime = "";
        JSONArray records = dataJson.getJSONArray("records");
        for (int i = 0; i < records.size(); i++) {
            JSONObject recordJson = records.getJSONObject(i);
            Integer id = recordJson.getInteger("id");
            String path = recordJson.getString("path");
            String personId = recordJson.getString("personId");
            long timestamp = recordJson.getLong("time");
            CdfaceacsOpenRecord openRecord = new CdfaceacsOpenRecord();
            openRecord.setId(id+"");
            //openRecord.setCapturePic(path);// 由于是局域网，所以在外网获取不到抓拍图片。用人脸照片代替
//            if(isFirst){
//                startTime = new SimpleDateFormat("yyyyMMddHHmmss").format(timestamp);
//            }
            openRecord.setOpenTime(DateUtil.getDateTimeOfTimestamp(timestamp));
            openRecord.setRecordType("人脸识别");
            if(device != null){
                openRecord.setSerialNum(serialNum);
                openRecord.setDeviceArea(device.getDeviceArea());
                openRecord.setDeviceName(device.getDeviceName());
            }
            if(workerMap.containsKey(personId)){
                CdfaceacsWorker worker = workerMap.get("personId");
                if(worker != null){
                    openRecord.setWorkTypeId(worker.getWorkTypeId());
                    openRecord.setWorkType(worker.getWorkType());
                    openRecord.setOpenUserId(worker.getId());
                    openRecord.setOpenUser(worker.getName());
                    openRecord.setPhone(worker.getPhone());
                    openRecord.setTeamId(worker.getTeamId());
                    openRecord.setTeam(worker.getTeam());
                    openRecord.setPersonCode(worker.getPersonCode());
                    openRecord.setCapturePic(worker.getFaceData());
                }
            }else if("STRANGERBABY".equals(personId)){ //陌生人
                openRecord.setOpenUser("[陌生人]");
            }
            CdfaceacsOpenRecord record = openRecordMapper.selectByKey(id + "");
            if(record == null){
                openRecordMapper.insert(openRecord);
            }else {
                openRecordMapper.updateByKey(openRecord);
            }
        }
        //redisUtil.set(key,startTime);
    }
}
